package cloud.dandanit.itservice.service.impl;

import cloud.dandanit.itservice.entity.GiveLike;
import cloud.dandanit.itservice.mapper.GiveLikeMapper;
import cloud.dandanit.itservice.service.GiveLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luokai
 * @since 2022-07-03
 */
@SuppressWarnings({"UnnecessaryLocalVariable", "AlibabaUndefineMagicConstant", "ConstantConditions", "FieldCanBeLocal"})
@Service
public class GiveLikeServiceImpl extends ServiceImpl<GiveLikeMapper, GiveLike> implements GiveLikeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private final String giveLikeId = "1194556896025845666";


    /**
     * 获取点赞数
     * @return 点赞数
     */
    @Override
    public Integer getGiveLikeNum() {


        if (redisTemplate.opsForValue().get("likeNum") != null) {
            Integer likeNumRedis = Integer.valueOf(redisTemplate.opsForValue().get("likeNum"));
            return likeNumRedis;

        } else {

            GiveLike giveLike = this.getOne(null);
            Integer likeNum = giveLike.getLikeNum();
            redisTemplate.opsForValue().set("likeNum", String.valueOf(likeNum));
            return likeNum;
        }

    }

    /**
     * 增加点赞数(存redis)
     * @param likeNum 点赞数
     */
    @Override
    public void addGiveLikeNumToRedis(String likeNum) {

        redisTemplate.opsForValue().set("likeNum", likeNum,3, TimeUnit.MINUTES);
    }

    /**
     * 增加点赞数(从redis转存数据库)
     */
    @Override
    public void addGiveLikeNumFromRedisToMysql() {

        if (redisTemplate.opsForValue().get("likeNum")!=null) {
            Integer likeNum = Integer.valueOf(redisTemplate.opsForValue().get("likeNum"));
            GiveLike giveLike = new GiveLike();
            giveLike.setId(giveLikeId);
            giveLike.setLikeNum(likeNum);
            this.updateById(giveLike);

            //删除redis数据
            redisTemplate.delete("likeNum");
        }
    }
}
